package com.atwu.wl2022.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 登录拦截，当未登录时，直接访问登录才能访问的某个页面，直接抛异常，跳转到异常页面
 * @author wulejay
 */
public class UserLoginInterceptor implements HandlerInterceptor {

	/**
	 * 目标方法执行之前
	 * @param request 请求域
	 * @param response 响应域
	 * @param handler 头信息
	 * @return 返回错误页面
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
		//登陆检查逻辑
		HttpSession session = request.getSession();
		Object loginUser = session.getAttribute("loginUserId");

		if(loginUser!=null){
			return true;
		}else {
			//否则跳转到博客首页
			response.sendRedirect(request.getContextPath()+"/");
			return false;
		}
	}
}
